/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package input;

import java.util.Arrays;
import java.util.regex.PatternSyntaxException;

import main.CommandSettings;
import main.Main;

import org.apache.log4j.Logger;

/**
 * This class parses the commands and formats the information
 * 
 * 
 */
public class Parser {
   /**
    * Checks if the message is a command. If it is, the message is returned, minus the command prefix. If the message contained an
    * alias, the alias is switched out for the base command instead. Returns an empty string if no command was found
    * 
    * @param message
    * @return
    */
   public static String isCommand(final String message) {
	  String cmd = "";
	  if (message.startsWith(Main.getBotSettings().getCommandPrefix()) && message.length() > 1) {
		 cmd = message.substring(1);
	  } else
		 return "";
	  try {
		 String currentCommand = cmd;
		 if (cmd.indexOf(' ') != -1) {
			currentCommand = cmd.substring(0, cmd.indexOf(' '));
		 }
		 String baseCommand = CommandSettings.INSTANCE.getBaseCommand(currentCommand);
		 if ("".equals(baseCommand))
			return "";
		 else {
			cmd = cmd.replaceFirst(currentCommand, baseCommand);
		 }
	  } catch (IndexOutOfBoundsException e) {
		 Logger.getLogger("Error").error("", e);
	  } catch (PatternSyntaxException e) {
		 Logger.getLogger("Error").error("", e);
	  }
	  return cmd;
   }

   /**
    * Parses the command and returns it as an IRCCommand object
    * 
    * @param message
    * @return
    */
   public static IRCCommand parseCommand(final String message, final int source, final String sender, final String channel) {
	  String[] p = message.split(" ");
	  for (int i = 0; i < p.length; ++i) { // clearing all commas from integers and doubles
		 if (p[i].matches("[0-9,]") || p[i].matches("[0-9,.]")) {
			p[i] = p[i].replace(",", "");
		 }
	  }
	  final IRCCommand pList = new IRCCommand(source, sender, channel, Arrays.asList(p));

	  return pList;
   }
}
